package deepbrain.simnetwork.task;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import deepbrain.simnetwork.engine.SimEngine;
import deepbrain.simnetwork.monitor.MonitorAdapter;

/**
 * 
 * 
 * @author Li Yang
 * @create 2009-2-26
 */
public class ConcurrentGroupTask extends Task {

	private static final long serialVersionUID = -2060226094145892095L;

	protected List<Task> tasks;
	// protected Set<Task> finishedTasks;
	protected int numOfFinishedTasks;
	protected boolean finished;
	protected Object waitObject = new Object();

	public ConcurrentGroupTask() {
		// finishedTasks = Collections.synchronizedSet(new HashSet<Task>());
		tasks = new ArrayList<Task>();
	}

	@Override
	public void runTask() {
		finished = false;
		SimEngine engine = threadLocalEngine.get();
		numOfFinishedTasks = 0;
		for (Task task : tasks) {
			task.addMonitor(new MonitorAdapter<Task>(true) {
				@Override
				public void onTaskFinish(Task task) {
					taskFinish();
				}
			});
			engine.runTask(task);
		}
		synchronized (waitObject) {
			while (!finished)
				try {
					waitObject.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		}
	}

	public synchronized void taskFinish() {
		// System.out.println(numOfFinishedTasks);
		if ((++numOfFinishedTasks) >= tasks.size()) {
			// System.out.println("in~~~~~~~~");
			finished = true;
			synchronized (waitObject) {
				waitObject.notify();
			}
		}
	}

	public void addTask(Task task) {
		tasks.add(task);
	}

	public void addTask(Collection<Task> task) {
		tasks.addAll(task);
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void removeTask(Task task) {
		tasks.remove(task);
	}

	public void removeTask(Collection<Task> task) {
		tasks.removeAll(task);
	}

}
